require 'View/UIBase/UIBase'

UIFlashGift = UIBase.New(PanelResNames.UIFlashGift)

function UIFlashGift.Init(func, id)
    UIFlashGift.activeId = id;
    UIBase.Init(UIFlashGift,func);
end

-- 创建回调
function UIFlashGift:OnCreate()
    --AddUIPackageDepend(PanelResNames.UIFlashGift,"FUI/BusinessAtlas")
    self.content = self:SetDynamicList(self:GetChild("list"),self.updateItem, nil, true)
    self.backtext = self:GetChild("backtext")
    self.nexttext = self:GetChild("nexttext")
    self.leftshowController = self:GetController("leftshow")
    self.rightshowController = self:GetController("rightshow")
    self:addEvent();
end

-- 显示
function UIFlashGift:OnEnable()
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.FlashGift) then
        self:OnClose();
        return ;
    end
    logicMgr.FlashGiftManager.setRedDots(true);
    FireEvent(Config.EventType.Fresh_FlashGiftRedDot);
    logicMgr.HeroManager.setGetNewHeroShow(true);
    self.selectGiftIds = {};
    self:Refresh();
end

function UIFlashGift:addEvent()
    self:RegisterOnClick(self:GetChild("bgClose"),self.OnClose);
    self:RegisterOnClick(self:GetChild("left"),self.OnScrollToLast);
    self:RegisterOnClick(self:GetChild("right"),self.OnScrollToNext);
    self:RegisterEvent(Config.EventType.Fresh_FuncMenuData,self.Refresh);
end

function UIFlashGift:removeEvent()
    self.content.scrollPane.onScrollEnd:Clear();
end

function UIFlashGift:Refresh(id)
    if id ~= nil then
        self.activeId = id;
    end
    self:UpdateData();
end

function UIFlashGift:UpdateData()
    self.giftIdList = logicMgr.FlashGiftManager.getShowFunFlashGiftList();
    if #self.giftIdList <= 0 then
        self:OnClose();
        return ;
    end
    self.countDownList = {};
    self.countDownNumList = {};
    self.optionItemTableData = G.dataTable["t_optionitem"];
    self.curIndex = 1;
    self.content.numItems = #self.giftIdList;
    local index = 1;
    for k, v in pairs(self.giftIdList) do
        if v.flashId == self.activeId then
            index = k;
            break;
        end
    end
    if #self.giftIdList > 0 then
        self.curIndex = index;
        self.content:ScrollToView(index - 1);
    end
    self:upadtePag();
    self.content.scrollPane.onScrollEnd:Add(function ()
        if self.content.scrollPane.currentPageX + 1 ~= self.curIndex then
            self.curIndex = self.content.scrollPane.currentPageX + 1;
            self:upadtePag();
        end
    end);
    self:RemoveAllTimeCall();
    self:TimeCall(self.OnCountDown, 1000, -1);
end

function UIFlashGift:updateItem(index, itemObj)
    local id = self.giftIdList[index].flashId;
    local serverData = logicMgr.FlashGiftManager.getGiftServerDataById(id);
    local tableData = logicMgr.FlashGiftManager.getGiftTableDataById(serverData.giftId);
    if tableData == nil then
        itemObj.visible = false;
        return ;
    end
    itemObj.visible = true;
    local selectGiftId = self.selectGiftIds[id] or tonumber(serverData.giftId);
    self.selectGiftIds[id] = tonumber(selectGiftId);
    local localTableData = logicMgr.FlashGiftManager.getGiftTableDataById(selectGiftId);
    local openTableData = logicMgr.FlashGiftManager.getGiftOpenTableDataById(serverData.conditionId);
    local description = itemObj:GetChild("description");
    local discount = itemObj:GetChild("Ratio");
    self.countDownList[id] = itemObj:GetChild("countDown");
    local buyCount = itemObj:GetChild("buyCount");
    local buyBtn = itemObj:GetChild("buy");
    local choose = itemObj:GetChild("choose");
    local bg = itemObj:GetChild("bg");
    local buyCountController = itemObj:GetController("showBuyCount");
    local isChooseController = itemObj:GetController("isChoose");
    local controller = itemObj:GetChild("list");
    -- 自选价格挡位
    local btnShowCtrl = itemObj:GetController("BtnShow");
    local btnPriceCtrl = itemObj:GetController("btn_price");
    local btnRecharge = {};
    for i = 1, 3 do
        table.insert(btnRecharge, itemObj:GetChild("Btn_recharge"..i));
    end
    for i = 1, 3 do
        btnRecharge[i].onClick:Clear();
    end
    btnShowCtrl.selectedIndex = 0;
    if tonumber(serverData.isOpen) == 1 and tableData.f_OptionalBagId ~= nil and tableData.f_OptionalBagId ~= "" then
        btnShowCtrl.selectedIndex = 1;
        local rechargeItems = {};
        table.insert(rechargeItems, tableData);
        local optionalBagId = tableData.f_OptionalBagId;
        for i = 1, table.nums(optionalBagId) do
            table.insert(rechargeItems, logicMgr.FlashGiftManager.getGiftTableDataById(optionalBagId[i]));
        end
        table.sort(rechargeItems, function(a, b)
            return a.f_Price < b.f_Price;
        end)
        for i = 1, 3 do
            local itemIndex = i;
            local itemCfg = rechargeItems[itemIndex];
            btnRecharge[i].title = "￥"..itemCfg.f_Price;
            if tonumber(itemCfg.f_BundleConsumptionId) == tonumber(selectGiftId) then
                btnPriceCtrl.selectedIndex = itemIndex;
            end
            btnRecharge[i].onClick:Add(function()
                localTableData = rechargeItems[itemIndex];
                selectGiftId = tonumber(localTableData.f_BundleConsumptionId);
                self.selectGiftIds[id] = selectGiftId;
                if tonumber(localTableData.f_BundleConsumptionId) == tonumber(serverData.giftId) then
                    self:updateItemInfo(discount, buyBtn, controller, isChooseController, choose, tableData, id, serverData.choseItems, serverData.giftId);
                else
                    local bundleConsumptionId = localTableData.f_BundleConsumptionId;
                    self:updateItemInfo(discount, buyBtn, controller, isChooseController, choose, localTableData, id, serverData.optionalChoseItemMap[tostring(bundleConsumptionId)], bundleConsumptionId);
                end
            end);
        end
    end

    bg.url = "ui://UIFlashGift/"..tableData.f_BundleConsumptionPic;
    description.text = getLanguage("BundleConsumption1000");
    if openTableData ~= nil then
        if openTableData.f_Condition == EnumConst.FlashGiftOpenType.Level then
            description.text = string.format(getLanguage("BundleConsumption1002"), openTableData.f_ConditionValue);
        elseif openTableData.f_Condition == EnumConst.FlashGiftOpenType.Dungeon then
            local cfg = logicMgr.MapManager.GetMapcfgByID(openTableData.f_ConditionValue);
            if cfg ~= nil then
                description.text = string.format(getLanguage("BundleConsumption1001"), cfg.f_ChapterId, cfg.f_StageNum);
            end
        elseif openTableData.f_Condition == EnumConst.FlashGiftOpenType.Line then
            description.text = string.format(getLanguage("BundleConsumption1004"), openTableData.f_ConditionValue);
        elseif openTableData.f_Condition == EnumConst.FlashGiftOpenType.Tower then
            description.text = string.format(getLanguage("BundleConsumption1003"), openTableData.f_ConditionValue);
        elseif openTableData.f_Condition == EnumConst.FlashGiftOpenType.Hero then
            local heroName = logicMgr.HeroManager.GetHeroNameByModelId(openTableData.f_ConditionValue);
            description.text = string.format(getLanguage("BundleConsumption1005"), heroName);
        end
    end
    if tableData.f_MaxCount <= 1 then
        buyCountController.selectedIndex = 0;
    else
        buyCountController.selectedIndex = 1;
        buyCount.text = getLanguage("SellLimit")..(tableData.f_MaxCount - serverData.buyCount).."/"..tableData.f_MaxCount;
    end
    buyBtn.onClick:Clear();
    buyBtn.onClick:Add(function() self:OnBuy(id, localTableData.f_ProductId, 1, localTableData.f_Price, selectGiftId); end);
    choose.onClick:Clear();
    if tonumber(selectGiftId) == tonumber(serverData.giftId) then
        self:updateItemInfo(discount, buyBtn, controller, isChooseController, choose, tableData, id, serverData.choseItems, selectGiftId);
    else
        self:updateItemInfo(discount, buyBtn, controller, isChooseController, choose, localTableData, id, serverData.optionalChoseItemMap[tostring(selectGiftId)], selectGiftId);
    end

    self.countDownNumList[id] = math.floor(serverData.endTime - HelperFunc.GetServerTime());
    self.countDownList[id].text = string.format(getLanguage("DailyConsumptionBannerTips20001", nil,"%s"),HelperFunc.GetTimeStr(self.countDownNumList[id]));
end

function UIFlashGift:updateItemInfo(discount, priceNode, list, isChooseController, choose, tableData, subId, choseItems, assistId)
    discount.url = tableData.f_Discount;
    priceNode.title = "￥"..tableData.f_Price;
    list:RemoveChildrenToPool();
    local itemData = decodeJsonStrToTabel(tableData.f_Item);
    isChooseController.selectedIndex = 1;
    for k, v in pairs(itemData) do
        local itemObj = list:AddItemFromPool();
        local item = itemObj:GetChild("item");
        local chooseController = itemObj:GetController("choose");
        local canChooseController = itemObj:GetController("canChoose");
        canChooseController.selectedIndex = 0;
        itemObj.onClick:Clear();
        if v[3] == 0 or v[3] == nil then
            chooseController.selectedIndex = 1;
            logicMgr.CostManager.RefreshItem(item, v);
        else
            choose.onClick:Clear();
            choose.onClick:Add(function()
                local _data = self:initChooseItem(choseItems or {}, tableData);
                self:showChooseTips(tableData.f_BundleConsumptionId, subId, nil, _data, assistId);
            end);
            itemObj.onClick:Add(function()
                local _data = self:initChooseItem(choseItems or {}, tableData);
                self:showChooseTips(tableData.f_BundleConsumptionId, subId, v[2], _data, assistId)
            end);
            if choseItems and choseItems[v[2]] then
                chooseController.selectedIndex = 1;
                canChooseController.selectedIndex = 1;
                local _data = self:initChooseItem(choseItems or {}, tableData);
                logicMgr.CostManager.RefreshItem(item, _data[v[2]]);
                item.onClick:Clear();
            else
                chooseController.selectedIndex = 0;
                isChooseController.selectedIndex = 0;
            end
        end
    end
end

function UIFlashGift:initChooseItem(serverData, tableData)
    local items = {};
    for i = 1, tableData.f_OptionCount do
        local data = {}
        if serverData[i] then
            data = self:findItemById(self:findChooseItemsByIdAndIndex(tableData.f_BundleConsumptionId, i), serverData[i].modelId);
        end
        table.insert(items, data);
    end
    return items;
end

function UIFlashGift:findChooseItemsByIdAndIndex(id, index)
    for k, v in pairs(self.optionItemTableData) do
        if v.f_BelongActiveId == tonumber(id) and v.f_OptionOrder == index then
            return decodeJsonStrToTabel(v.f_OptionItem);
        end
    end
    return {};
end

function UIFlashGift:findItemById(items, id)
    for k, v in pairs(items) do
        if v[1] == id then
            return v;
        end
    end
    return {};
end

function UIFlashGift:showChooseTips(id, flashId, index, _data, assistId)
    showUI(PanelNames.UIOptionalGiftTips, function (data)
        local serverData = logicMgr.FlashGiftManager.getGiftServerDataById(flashId);
        local data1 = {};
        for i = 1, #data do
            local data2 = {};
            data2.modelId = data[i][1];
            table.insert(data1, data2);
        end
        if tonumber(assistId) == tonumber(serverData.giftId) then
            serverData.choseItems = data1;
        else
            if serverData.optionalChoseItemMap == nil then
                serverData.optionalChoseItemMap = {};
            end
            serverData.optionalChoseItemMap[tostring(assistId)] = data1;
        end
        self.activeId = flashId;
        self:UpdateData();
    end, logicMgr.CostManager._FLASHGIFTID, id, flashId, index, _data, nil, assistId);
end

function UIFlashGift:OnCountDown()
    for k, v in pairs(self.giftIdList) do
        if self.countDownList[v.flashId] ~= nil and self.countDownNumList[v.flashId] ~= nil then
            self.countDownNumList[v.flashId] = self.countDownNumList[v.flashId] - 1;
            self.countDownList[v.flashId].text = string.format(getLanguage("DailyConsumptionBannerTips20001", nil,"%s"),HelperFunc.GetTimeStr(self.countDownNumList[v.flashId]));
            if self.countDownNumList[v.flashId] <= 0 then
                if self.giftIdList[self.curIndex] then
                    self.activeId = self.giftIdList[self.curIndex].flashId;
                end
                logicMgr.FlashGiftManager.removeOneFlashGift(self.activeId);
            end
        end
    end
end

function UIFlashGift:OnScrollToNext(evt)
    self.content.scrollPane:ScrollRight(1, true);
    self.curIndex = self.curIndex + 1;
    self:upadtePag();
end

function UIFlashGift:OnScrollToLast(evt)
    self.content.scrollPane:ScrollLeft(1, true);
    self.curIndex = self.curIndex - 1;
    self:upadtePag();
end

function UIFlashGift:upadtePag()
    if self.curIndex < 1 or self.curIndex > #self.giftIdList then
        return ;
    end
    if self.curIndex == 1 then
        self.leftshowController.selectedIndex = 0;
    else
        self.backtext.text = self.curIndex - 1;
        self.leftshowController.selectedIndex = 1;
    end
    if self.curIndex == #self.giftIdList then
        self.rightshowController.selectedIndex = 0;
    else
        self.nexttext.text = #self.giftIdList - self.curIndex;
        self.rightshowController.selectedIndex = 1;
    end
end

-- 购买
function UIFlashGift:OnBuy(activeId, payId, num, cheekItemMoney, giftId)
    local indexs = {};
    table.insert(indexs, activeId);
    table.insert(indexs, giftId);
    logicMgr.CostManager.getRewardByIdAndIndex(logicMgr.CostManager._FLASHGIFTID, indexs, payId, num, cheekItemMoney, nil, self, function ()
        self:onBuySuccess(activeId);
    end);
end

-- 购买成功
function UIFlashGift:onBuySuccess(activeId)
    if logicMgr.FlashGiftManager.buyOneFlashGiftByActiveId(activeId) then
        logicMgr.FlashGiftManager.removeOneFlashGift(activeId)
    end
end

-- 关闭
function UIFlashGift:OnClose()
    self:OnBack();
    logicMgr.HeroManager.setGetNewHeroShow();
    logicMgr.CostManager.showPopUpTips();
    self:RemoveAllTimeCall();
end

-- 隐藏
function UIFlashGift:OnDisable()
end

-- 卸载
function UIFlashGift:OnDestroy()
    self:removeEvent();
end

return UIFlashGift